/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import healthcare.coursework.model.Outlet;
import healthcare.coursework.model.Specialization;
import healthcare.coursework.model.Users;
import healthcare.coursework.service.UserService;
import java.sql.Timestamp;
import java.util.Date;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Row;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

/**
 *
 * @author Administrator
 */
public class EditStaff extends GenericAutowireComposer {

    private Combobox branch;
    private Label username;
    private Label lblBranch;
    private Label lblSpecification;
    private Textbox password;
    private Textbox fullName;
    private Datebox birthdate;
    private Radiogroup gender;
    private Label role;
    private Textbox phone;
    private Textbox address;
    private Textbox email;
    private Row labFunction;
    private Combobox typeOfLaboratory;
    private Row specFunction;
    private Combobox specification;
    private Window self;
    private Users staff;
    private UserService userService = util.Utility.getUtility().getUserService();

    public void onLoadForm(Event e) {
        setConstraint();
        setInfo();
    }

    private void setConstraint() {

        password.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validatePassword(cmpnt, o);
            }
        });


        fullName.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateFullname(cmpnt, o);
            }
        });

        birthdate.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateBirthDate(cmpnt, o);
            }
        });

        address.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validateAddress(cmpnt, o);
            }
        });

        phone.setConstraint(new Constraint() {

            @Override
            public void validate(Component cmpnt, Object o) throws WrongValueException {
                validatePhone(cmpnt, o);
            }
        });
//        email.setConstraint(new Constraint() {
//
//            @Override
//            public void validate(Component cmpnt, Object o) throws WrongValueException {
//                validateEmail(cmpnt, o);
//            }
//        });
    }

    public void validateEmail(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Please enter email");
        }
        if (!s.matches("^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\\.)+([A-Za-z0-9]{2,4}|museum)$")) {
            throw new WrongValueException(comp, "Invalid email");
        }
        if (userService.isEmailExisted(s)) {
            throw new WrongValueException(comp, "Email existed! Please choose another Email!");
        }
    }

    private void validatePassword(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Please enter new password");
        }
        if (!s.matches("^\\w{3,20}$")) {
            throw new WrongValueException(comp, "Password must be 3-20 alphanumeric characters");
        }
    }

    private void validateFullname(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Fullname cannot be empty");
        }
    }

    private void validateJob(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Job cannot be empty");
        }
    }

    private void validateBirthDate(Component comp, Object value) throws WrongValueException {
        Date d = (Date) value;
        if (d == null) {
            throw new WrongValueException(comp, "Birthdate cannot be empty");
        }
        if (d.after(new Date())) {
            throw new WrongValueException(comp, "Birthdate must be less than current date!!!");
        }
    }

    private void validateAddress(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Address cannot be empty");
        }
    }

    private void validatePhone(Component comp, Object value) throws WrongValueException {
        String s = (String) value;
        s = s.trim();
        if (s.length() < 1) {
            throw new WrongValueException(comp, "Phone cannot be empty");
        }
    }

    public void onReset(Event e) {
        setInfo();
    }

    public void onUpdate(Event e) {
        try {
            staff.setPassword(password.getValue());
            staff.setFullName(fullName.getValue());
            staff.setAddress(address.getValue());
            staff.setPhone(phone.getValue());
            staff.setDateOfBirth(new Timestamp(birthdate.getValue().getTime()));
            staff.setEmail(email.getValue());
           staff.setOutlet( (Outlet) branch.getSelectedItem().getValue());
            if (staff.getAuthorities().get(0).getAuthoritiesPK().getAuthority().equals("Laboratory")) {
                staff.setTypeOfLaboratory((String) typeOfLaboratory.getSelectedItem().getLabel());
                userService.edit(staff, null);
            }
            else {
                userService.edit(staff, (Specialization) lblSpecification.getAttribute("spec"));
            }
            Messagebox.show("The staff information has been modified!", "Information", Messagebox.OK, Messagebox.INFORMATION);
            self.onClose();
            Executions.sendRedirect("TrackStaff.do");
        } catch (InterruptedException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void onClose(Event e) {
        self.onClose();
        Executions.sendRedirect("TrackStaff.do");
    }

    private void switchFunction() {
        String authority = this.role.getValue();
        if (authority.equals("Laboratory")) {
            labFunction.setVisible(true);
            specification.setVisible(false);
            typeOfLaboratory.setText(staff.getTypeOfLaboratory());
        } else if (authority.equals("Doctor")) {
            labFunction.setVisible(false);
            specification.setVisible(true);
            lblSpecification.setValue(staff.getSpecialization().getSpecializationName());
            lblBranch.setAttribute("spec", staff.getSpecialization());
        } else {
            labFunction.setVisible(false);
            specification.setVisible(false);
        }

    }

    private void setInfo() {
        staff = (Users) arg.get("user");
        username.setValue(staff.getUsername());
        password.setValue(staff.getPassword());
        fullName.setValue(staff.getFullName());
        address.setValue(staff.getAddress());
        phone.setValue(staff.getPhone());
        birthdate.setValue(new Date(staff.getDateOfBirth().getTime()));
        email.setValue(staff.getEmail());
        String authority = staff.getAuthorities().get(0).getAuthoritiesPK().getAuthority();
        role.setValue(authority);
        lblBranch.setValue(staff.getOutlet().getOutletName());
        branch.setText(staff.getOutlet().getOutletName());
        branch.setModel(new ListModelList(new ListModelList(userService.outlets())));
        lblBranch.setAttribute("outlet", staff.getOutlet());
        specification.setModel(new ListModelList(userService.specializations()));

        switchFunction();
    }

     public void onSetBranchInfo(Event e) {
         
    }

    public void onSetSpecInfo(Event e) {
        Specialization s = (Specialization) specification.getSelectedItem().getValue();
        lblSpecification.setValue(s.getSpecializationName());
        specification.setText(lblSpecification.getValue());
        lblSpecification.setAttribute("spec", s);
    }

//    private void loadBranchInformation(){
//        List<Listitem> items=branch.getItems();
//        for (Listitem listitem : items) {
//            if(listitem.getValue().equals(staff.getOutlet().getOutletId()))
//            {
//                branch.setSelectedIndex(listitem.getIndex());
//            }
//        }
//    }
    public void onLoadSpec(Event e) {
        

    }

}
